package com.huifaapp.mall.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.Request;
import com.google.gson.Gson;
import com.huifaapp.mall.R;
import com.huifaapp.mall.activity.HomeLivingMoneyFragement;
import com.huifaapp.mall.activity.HtmlActivity;
import com.huifaapp.mall.activity.JDred_packetActivity;
import com.huifaapp.mall.activity.Red_PacketActivity;
import com.huifaapp.mall.activity.ShopCartActivity;
import com.huifaapp.mall.activity.ShopYouhuiShareActivity;
import com.huifaapp.mall.activity.TmallhomepageFragment;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.bean.GoodsClassifyListData;
import com.huifaapp.mall.bean.JDcomjPlistBean;
import com.huifaapp.mall.bean.JDlianjie;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.view.NumberSelectView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.kepler.jd.Listener.LoginListener;
import com.kepler.jd.login.KeplerApiManager;
import com.kepler.jd.sdk.exception.KeplerBufferOverflowException;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 天猫页面精选适配器
 */

public class TmallchoicenessAdapter extends XRecyclerView.Adapter<TmallchoicenessAdapter.MyViewHolder> implements View.OnClickListener {
    private List<JDcomjPlistBean.DataBean.ListBean> list ;
    private Context context;
    private List<Boolean> isChecked;    //每个条目是否为选中
    private List<String> numbers;       //每个条目应显示的数字
    private List<Integer> checkedIndex;   //保存选中的下标
    private List<CheckBox> checkBox;      //保存选中的checkBox
    private int maxChecked = 9;       //最多选中几个
    private int checkedNumber = 0;    //选中的个数
    private int length = 500;  //条目的总长
    String shop;
    private JDlianjie jDlianjiebean;
    private String datayouhui;
    private int location;
    String  datalisnajie;

    public TmallchoicenessAdapter(List<JDcomjPlistBean.DataBean.ListBean> list, Context context, String shop) {
        this.list = list;
        this.context = context;
        this.shop=shop;
        isChecked = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            isChecked.add(false);
        }
        numbers = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            numbers.add("");
        }
        checkedIndex = new ArrayList<>();
        checkBox = new ArrayList<>();
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View recyclerViewItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.itme_tmall_choiceness, parent, false);
        recyclerViewItem.setOnClickListener(this);
        return  new MyViewHolder(recyclerViewItem);
    }
    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holder.itme_tmall_text_name.setText("\t\t\t\t"+list.get(position).getGoodsName());
        Glide.with(context).load(list.get(position).getMainImageUrl()).into(holder.itme_tmall_imge);
        holder.itme_tmall_price.setText("¥"+list.get(position).getPrice());
        holder. itme_tmall_conprice.setText(list.get(position).getConPrice());
        holder. itme_tmall_price.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG);
        holder.itme_tmall_totalSales.setText(list.get(position).getTotalSales());

        holder.itme_tmall_couponMoney.setText("降"+list.get(position).getCouponMoney()+"元");
        holder.itme_tmall_checkBox.setChecked(isChecked.get(position));
        holder.itme_tmall_checkBox.setText(numbers.get(position));
        if( list.get(position).getWlCommission()==0|| list.get(position).getWlCommission()==0.0|| list.get(position).getWlCommission()==0.00){
            holder.tv_tmall_lijifenxiang.setText("立即分享" );
            holder.tv_tmall_lijifenxiang_no.setText("立即分享" );
        }else {
            holder.tv_tmall_lijifenxiang.setText("分享赚 ¥" + list.get(position).getWlCommission());
            holder.tv_tmall_lijifenxiang_no.setText("分享赚 ¥" + list.get(position).getWlCommission());
        }
        if (SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            holder.itme_tmall_checkBox.setVisibility(View.VISIBLE);
            holder.tv_tmall_lijifenxiang_pt.setVisibility(View.GONE);
            holder.tv_tmall_lijifenxiang.setVisibility(View.VISIBLE);
        }else{
            holder.itme_tmall_checkBox.setVisibility(View.GONE);
            holder.tv_tmall_lijifenxiang_pt.setVisibility(View.VISIBLE);
            holder.tv_tmall_lijifenxiang.setVisibility(View.GONE);
        }
        if(list.get(position).getSpuPlatform().equals("jd")){
            holder.iv_tmall_jdOryh.setImageResource(R.drawable.jingdong);
        }else{
            holder.iv_tmall_jdOryh.setImageResource(R.drawable.youhui);
        }
        Log.e("position",position+"");
        holder.itme_tmall_checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean check;
                if (checkedNumber < maxChecked) {
                    if (!isChecked.get(position)) {
                        checkedIndex.add(position);
                        checkBox.add(holder.itme_tmall_checkBox);
                        checkedNumber++;
                        setText();
                    } else {
                        clearText(position, holder.itme_tmall_checkBox);
                    }
                    check = !isChecked.get(position);
                } else {
                    if (checkedNumber == maxChecked && isChecked.get(position)) {
                        clearText(position, holder.itme_tmall_checkBox);
                    } else {
                        Toast.makeText(context, "最多只能选" + maxChecked + "个", Toast.LENGTH_SHORT).show();
                    }
                    check = false;
                }
                isChecked.set(position, check);
                holder.itme_tmall_checkBox.setChecked(isChecked.get(position));
            }
        });
        final Integer tag = new Integer(position);
        //解决RecyclerView和checkBox问题
        holder.itme_tmall_checkBox.setTag(tag);
        if(shop.equals("shop")){
            if (ShopCartActivity.hmap.containsKey(tag)) {
                holder.itme_tmall_checkBox.setChecked(ShopCartActivity.hmap.get(tag));
            } else {
                holder.itme_tmall_checkBox.setChecked(false);//true or false 都可以，看实际需求
            }
        } else if(shop.equals("home")){
            if (HomeLivingMoneyFragement.hmap.containsKey(tag)) {
                holder.itme_tmall_checkBox.setChecked(HomeLivingMoneyFragement.hmap.get(tag));
            } else {
                holder.itme_tmall_checkBox.setChecked(false);//true or false 都可以，看实际需求
            }
        }
        else {
            if (TmallhomepageFragment.hmap.containsKey(tag)) {
                holder.itme_tmall_checkBox.setChecked(TmallhomepageFragment.hmap.get(tag));
            } else {
                holder.itme_tmall_checkBox.setChecked(false);//true or false 都可以，看实际需求
            }
        }
        Contig.checkedIndexltmalgrid = checkedIndex;
        holder.itemView.setTag(position);
        holder.tv_tmall_lijifenxiang_no.setVisibility(View.GONE);
        for (int s = 0; s < Contig.ShareListtmll.size(); s++) {
            if (list.get(position).getId().equals(Contig.ShareListtmll.get(s))) {
                holder.tv_tmall_lijifenxiang_no.setVisibility(View.VISIBLE);
                holder.tv_tmall_lijifenxiang.setVisibility(View.GONE);
                Log.e("5647","youbianhua          "+list.get(position).getId());


            }
        }
        holder.tv_tmall_lijifenxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(context, ShopYouhuiShareActivity.class);
                intent.putExtra("id",list.get(position).getId());
                context.startActivity(intent);
                holder.tv_tmall_lijifenxiang_no.setVisibility(View.VISIBLE);
                holder.tv_tmall_lijifenxiang.setVisibility(View.GONE);
            }
        });
        holder.rl_shar_item_gv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(context, Red_PacketActivity.class);
//                intent.putExtra("shopid", list.get(position).getId());
//                intent.putExtra("typex", "yh");
//                context.startActivity(intent);

                if (list.get(position).getSpuPlatform().equals("yh")) {
                    Intent intent = new Intent(context, Red_PacketActivity.class);
                    intent.putExtra("shopid", list.get(position).getId());
                    intent.putExtra("typex", list.get(position).getSpuPlatform());
                    context.startActivity(intent);
                } else {
                    location = position;
                    if (list.get(position).getSpuPlatform().equals("yh")) {
                        Intent intent = new Intent(context, Red_PacketActivity.class);
                        intent.putExtra("shopid", list.get(position).getId());
                        intent.putExtra("typex",list.get(position).getSpuPlatform());
                        context.startActivity(intent);
                    } else {
                        if (list.get(position).getSpuPlatform().equals("jd")) {
                            if (list.get(position).getCouponMoney().equals("")) {
                                initJDputong();
                                if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                    try {
                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                    } catch (KeplerBufferOverflowException e) {
                                        e.printStackTrace();
                                    }

                                }else {
                                    final LoginListener mLoginListener = new LoginListener() {
                                        @Override
                                        public void authSuccess(Object token) {
                                            // TODO Auto-generated method stub
                                            Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
                                            //                showToken();

                                            if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                try {
                                                    KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                } catch (KeplerBufferOverflowException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }

                                        @Override
                                        public void authFailed(int errorCode) {
                                            // TODO Auto-generated method stub
                                            switch (errorCode) {
                                                case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                default:
                                                    break;
                                            }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                            Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                        }
                                    };
                                    KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
                                }
//                                Intent intent = new Intent(context, HtmlActivity.class);
//                                intent.putExtra("data", datalisnajie);
//                                intent.putExtra("shopid", list.get(location).getId());
//                                context.startActivity(intent);
                            }
                            if (list.get(position).getCouponMoney() != "") {
                                if (list.get(position).getCouponMoney().equals("0.0")) {

                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                    map.put("spuId", list.get(location).getId());
                                    map.put("appid", AUniqueIdentifier.getDeviceId(context));

                                    OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+list.get(position).getSpuPlatform()+"/getConUrl").build().execute(new StringCallback() {
                                        @Override
                                        public void onError(com.squareup.okhttp.Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            Log.e("优惠二和一数据", response);
                                            Gson gson = new Gson();
                                            jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                            datayouhui = jDlianjiebean.getData();
                                            if (jDlianjiebean.getCode().equals("10000")) {
                                                Intent intent = new Intent(context, JDred_packetActivity.class);
                                                intent.putExtra("shopid", list.get(location).getId());
                                                context.startActivity(intent);
                                            }
                                        }
                                    });

                                } else {
                                    Log.e("优惠二和一链接接口", ApiManager.BASE_NIUPAI_URL+list.get(position).getSpuPlatform()+"/getConUrl" + "?token=" + SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN) + "&spuId=" + list.get(location).getId() + "&appid=" + AUniqueIdentifier.getDeviceId(context));
                                    Map<String, String> map = new HashMap<>();
                                    map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
                                    map.put("spuId", list.get(location).getId());
                                    map.put("appid", AUniqueIdentifier.getDeviceId(context));

                                    OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+list.get(position).getSpuPlatform()+"/getConUrl").build().execute(new StringCallback() {
                                        @Override
                                        public void onError(com.squareup.okhttp.Request request, Exception e) {

                                        }

                                        @Override
                                        public void onResponse(String response) {
                                            Log.e("优惠二和一数据9", response);
                                            Gson gson = new Gson();
                                            jDlianjiebean = gson.fromJson(response, JDlianjie.class);
                                            datayouhui = jDlianjiebean.getData();
                                            if (jDlianjiebean.getCode().equals("10000")) {
                                                if (jDlianjiebean.getData() != null) {
                                                    if(KeplerApiManager.getWebViewService().isKeplerLogined()){
                                                        try {
                                                            KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                        } catch (KeplerBufferOverflowException e) {
                                                            e.printStackTrace();
                                                        }

                                                    }else {
                                                        final LoginListener mLoginListener = new LoginListener() {
                                                            @Override
                                                            public void authSuccess(Object token) {
                                                                // TODO Auto-generated method stub
                                                                Toast.makeText(context, token + "", Toast.LENGTH_SHORT).show();
                                                                //                showToken();

                                                                if (KeplerApiManager.getWebViewService().isKeplerLogined()) {
                                                                    try {
                                                                        KeplerApiManager.getWebViewService().openJDUrlWebViewPage(jDlianjiebean.getData() + "&userid" + SPUtils.getInstance().getString(SPConstants.KEY_USERID), "kepler_customer_Info");
                                                                    } catch (KeplerBufferOverflowException e) {
                                                                        e.printStackTrace();
                                                                    }
                                                                }

                                                            }

                                                            @Override
                                                            public void authFailed(int errorCode) {
                                                                // TODO Auto-generated method stub
                                                                switch (errorCode) {
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_Init:// 初始化失败 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_InitIng:// 初始化没有完成 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_openH5authPageURLSettingNull://跳转url // 为null break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_getTokenErr:// 获取失败(OAuth授权之后，获取cookie过程出错) break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_User_Cancel:// 用户取消 break;
                                                                    case KeplerApiManager.KeplerApiManagerLoginErr_AuthErr_ActivityOpen://打开授权页面失败 break;
                                                                    default:
                                                                        break;
                                                                }
//                Toast.makeText(AllOrderActivity.this, errorCode + ":authFailed", Toast.LENGTH_SHORT).show();
                                                                Log.e("jdSHOUQUAN", errorCode + ":authFailed");
                                                            }
                                                        };
                                                        KeplerApiManager.getWebViewService().login((Activity) context, mLoginListener);
                                                    }
//                                                    Intent intent = new Intent(context, HtmlActivity.class);
//                                                    intent.putExtra("shopid", list.get(location).getId());
//                                                    intent.putExtra("data", jDlianjiebean.getData());
//                                                    context.startActivity(intent);

                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    //普通二和一链接
    private void initJDputong(){
        try {
            Map<String, String> map = new HashMap<String, String>();
            map.put("spuId", list.get(location).getId());
            map.put("appid", AUniqueIdentifier.getDeviceId(context));
            map.put("token", SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
            Log.e("京东二合一转链", ApiManager.BASE_NIUPAI_URL+list.get(location).getSpuPlatform()+"/getUrl" + "?spuId=" + list.get(location).getId() + "&appId=" + AUniqueIdentifier.getDeviceId(context) + "&token=" + SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN));
            OkHttpUtils.post().params(map).url(ApiManager.BASE_NIUPAI_URL+list.get(location).getSpuPlatform()+"/getUrl").build().execute(new StringCallback() {
                @Override
                public void onError(com.squareup.okhttp.Request request, Exception e) {

                }
                @Override
                public void onResponse(String response) {
                    Log.e("fgdgfe", response);
                    Gson gson = new Gson();
                    JDlianjie jDlianjie = gson.fromJson(response, JDlianjie.class);
                    datalisnajie = jDlianjie.getData();
                    Log.e("kfjsdkghdfk", datalisnajie);

                }
            });
        }catch (Exception e){

        }
    }
    public void clearText(int position, CheckBox cb_checked) {
        for (int i = 0; i < checkedIndex.size(); i++) {
            if (checkedIndex.get(i) == position) {
                numbers.set(position, "");
                checkedIndex.remove(i);
                checkBox.remove(i);
                break;
            }
        }
        checkedNumber--;
        setText();
        numbers.set(position, "");
        cb_checked.setText("");
    }

    public void setText() {
        for (int i = 0; i < checkedIndex.size(); i++) {
            numbers.set(checkedIndex.get(i), (i + 1) + "");
            checkBox.get(i).setText(numbers.get(checkedIndex.get(i)));
        }
    }




    //itme点击接口回调
    public interface MyItemclickListener {
        void itemclick(View view, int position);
    }
    public MyItemclickListener mMyItemclickListener;

    public void setmMyItemclickListener(MyItemclickListener mMyItemclickListener) {
        this.mMyItemclickListener = mMyItemclickListener;
    }
    @Override
    public int getItemCount() {
        int count = (list == null ? 0 : list.size());
        return count;
    }





    @Override
    public void onClick(View v) {
        if (mMyItemclickListener != null) {
            mMyItemclickListener.itemclick(v, (Integer) v.getTag());
        }

    }

    class MyViewHolder extends RecyclerView.ViewHolder {


        private final ImageView itme_tmall_imge;
        private final TextView itme_tmall_text_name;
        private final TextView itme_tmall_price;
        private TextView itme_tmall_conprice;
        private final TextView itme_tmall_totalSales;
        private final TextView itme_tmall_couponMoney;
        private  CheckBox itme_tmall_checkBox;
        private TextView tv_tmall_lijifenxiang_no;
        private TextView tv_tmall_lijifenxiang;
        private RelativeLayout rl_shar_item_gv;
        private TextView tv_tmall_lijifenxiang_pt;
        private ImageView iv_tmall_jdOryh;
        public MyViewHolder(View itemView) {
            super(itemView);
            itme_tmall_imge = (ImageView) itemView.findViewById(R.id.itme_tmall_imge);
            itme_tmall_text_name = (TextView) itemView.findViewById(R.id.itme_tmall_text_name);
            itme_tmall_price = (TextView) itemView.findViewById(R.id.itme_tmall_price);
            itme_tmall_conprice = (TextView) itemView.findViewById(R.id.itme_tmall_discountprice);
            itme_tmall_checkBox= (CheckBox) itemView.findViewById(R.id.itme_tmall_checkBox);
            itme_tmall_totalSales = (TextView) itemView.findViewById(R.id.itme_tmall_totalSales);
            itme_tmall_couponMoney = (TextView) itemView.findViewById(R.id.itme_tmall_couponMoney);
            tv_tmall_lijifenxiang= (TextView) itemView.findViewById(R.id.tv_tmall_lijifenxiang);
            tv_tmall_lijifenxiang_no= (TextView) itemView.findViewById(R.id.tv_tmall_lijifenxiang_no);
            rl_shar_item_gv= (RelativeLayout) itemView.findViewById(R.id.rl_shar_item_gv);
            tv_tmall_lijifenxiang_pt= (TextView) itemView.findViewById(R.id.tv_tmall_lijifenxiang_pt);
            iv_tmall_jdOryh= (ImageView) itemView.findViewById(R.id.iv_tmall_jdOryh);
        }
    }

}
